# -*- coding=utf-8 -*-
from flask_security import UserMixin, RoleMixin, utils, SQLAlchemyUserDatastore

from src.utils.models import db
from .user import User, Role, RolesUsers


def create_user(username, email, password):
    """创建用户"""
    user = User()
    user.username = username
    user.email = email
    user.password = utils.hash_password(password)
    user.roles.append(get_role())
    db.session.add(user)
    db.session.commit()


def create_role(name, description):
    """创建用户"""
    role = Role()
    role.name = name
    role.description = description
    db.session.add(role)
    db.session.commit()


def create_roles_users(rolename, username):
    """创建用户角色授权"""
    role = Role.query.filter(Role.name == rolename).first()
    user = User.query.filter(User.username == username).first()
    rs = roles_users(user_id=user.id, role_id=role.id)
    db.session.add(rs)
    db.session.commit()


def get_datastore(db):
    return SQLAlchemyUserDatastore(db, User, Role)


def get_users():
    users = User().query.all()
    users_info = {'users': []}
    for each in users:
        user = User.query.filter(User.username == each.username).first()
        users_info['users'].append(user.get_setup())
    return users_info


def get_user(email):
    return User.query.filter(User.email == email).first()


def get_user_id(id):
    return User.query.get(id)


def get_role(role_name='user'):
    return Role.query.filter(Role.name == role_name).first()
